<?php

namespace App\Http\Controllers\admin;
use DB;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Requests\keywords\AddRequests;
use App\Http\Controllers\Controller;

class HotkeywordsController extends Controller
{
    /**
    * 热搜词汇添加 
    * /admin/hotkeywords/add
    * /admin/hotkeywords/insert
    */
    //添加页面
    public function getAdd() { 
        return view("hotkeywords.add");
    }

    //执行添加
    public function postInsert(addRequests $request) {
        
        // 过滤字段
        $data = $request -> except(["_token"]);
        
        //插入
        $res = DB::table("hot_keywords") -> insert($data);

        //解析结果集
        if ($res) {

            //成功，提示并跳转
            return redirect("/admin/hotkeywords/index") -> with("success", "添加成功！");
        } else {

            //失败，提示并返回
            return back() -> with("error", "添加失败！");
        }
    }

    /**
    * 热搜词汇浏览 
    * /admin/hotkeywords/index
    */
    public function getIndex(Request $request){
            
        //查询数据库
        $res = DB::table("hot_keywords") -> where(function($query)use($request) {
            if($request -> input('keywords')) {
                $query -> where("name","like","%".$request -> input("keywords")."%");
            }
        }) -> orderby("num","desc") -> paginate($request -> input("num", 10));
        
        //返回浏览页面
        return view("hotkeywords.index", ["list" => $res, "request" => $request -> all()]);
    }

     /**
    * 热搜词汇浏览 
    * /admin/hotkeywords/delete
    */
    public function getDelete($id) {

        //执行删除语句
        $res = DB::table("hot_keywords") -> where("id", $id) -> delete();

        //解析结果集
        if($res) {

            //成功提示并跳转
            return redirect("/admin/hotkeywords/index") -> with("success", "删除成功！");
        } else {

            //失败返回并提示
            return back() -> with("error", "删除失败！");
        }
    }

    /**
    * 热搜词汇状态修改
    * /admin/hotkeywords/edit
    * /admin/hotkeywords/update
    */
    public function getStatus($status,$id) {
        
        //处理数据
        if ($status == 0) {
            $status = 1;    //原状态关闭时开启
        } else {
            $status = 0;    //原状态开启时关闭
        }
        
        //执行修改
        $res = DB::table("hot_keywords") -> where("id", $id) -> update(["status" => $status]);

        //解析结果集
        if ($res) {
            
            //成功时跳转
            return redirect("/admin/hotkeywords/index");
        } else {

            //失败是返回并提示
            return back() -> with("error", "修改失败!");
        }
    }
}
